package cn.edu.java.thread.锁;

import lombok.SneakyThrows;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockDemo {
    private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static int sharedResource = 0;


    public static void main(String[] args) {
        Runnable write = new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                lock.writeLock().lock();
                try {
                    // 写入共享资源
                    sharedResource = 42;
                    Thread.sleep(1000);
                    System.out.println("Writer thread writes: " + sharedResource);
                } finally {
                    lock.writeLock().unlock();
                }
            }
        };

        Runnable read = new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                lock.readLock().lock();
                try {
                    // 读取共享资源
                    Thread.sleep(1000);
                    System.out.println("Reader thread reads: " + sharedResource);
                } finally {
                    lock.readLock().unlock();
                }
            }
        };

        new Thread(read).start();
        new Thread(read).start();
        new Thread(write).start();  // 写访问优先
        new Thread(read).start();
        new Thread(read).start();
    }
}
